<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="商品分类" prop="parentName">
        <el-popover
          ref="dataListPopover"
          placement="bottom-start"
          trigger="click">
          <el-tree
            :data="dataList"
            :props="dataListTreeProps"
            node-key="id"
            ref="dataListTree"
            @current-change="dataListTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:dataListPopover :readonly="true" placeholder="点击选择上级菜单" class="menu-list__input"></el-input>
      </el-form-item>
      <el-form-item label="产品名称" prop="productCode">
        <el-select v-model="dataForm.productCode" @change="getProductInfo()" placeholder="选择产品" style="width:250px;">
          <el-option label="选择产品" value=""></el-option>
          <el-option v-for="(item, index) in dataForm.product" :label="item.productName + ' - '+ (item.shopName?item.shopName:'总部')" :key="item.id" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出库类型" prop="ckOutType">
        <el-select v-model="dataForm.ckOutType" @change="changeType()" placeholder= "出库类型" style="width:250px;">
          <el-option v-for="(item, index) in typeOptions"
                     :label="item.label"
                     :key="item.value"
                     :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="校区" prop="shopId" v-if="shopShow">
        <el-select v-model="dataForm.shopId" placeholder= "校区" style="width:250px;">
          <el-option v-for="(item, index) in shopids"
                     :label="item.shopName"
                     :key="item.shopName"
                     :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName" v-if="!shopShow">
        <el-input v-model="dataForm.studentName" placeholder="" ></el-input>
      </el-form-item>
      <el-form-item label="剩余库存" prop="leftNum">
        <el-input v-model="dataForm.leftNum" placeholder="" v-bind:disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="出库数量" prop="outNum">
        <el-input v-model="dataForm.outNum" placeholder="出库数量"></el-input>
      </el-form-item>
      <!-- <el-form-item label="客户id" prop="userId">
        <el-input v-model="dataForm.userId" placeholder="客户id"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input v-model="dataForm.status" placeholder="状态 （1：创建 2：审核通过）"></el-input>
      </el-form-item> -->
      <el-form-item label="收件人" prop="consignee">
        <el-input v-model="dataForm.consignee" placeholder="收件人"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="地址"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          productCode: '',
          outNum: 0,
          userId: '',
          status: '',
          consignee: '',
          mobile: '',
          address: '',
          remark: '',
          creator: '',
          createTime: '',
          updator: '',
          updateTime: '',
          pid: '',
          pid2: '',
          fatherCategory: [],
          category: [],
          product: [],
          parentId: 0,
          parentName: '',
          leftNum: 0,
          shopId: '',
          ckOutType: '0',
          studentName: ''
        },
        shopShow: false,
        dataRule: {
          ckOutType: [{
            required: true,
            message: '出库类型不能为空',
            trigger: 'blur'
          }],
          shopId: [{
            required: true,
            message: '校区不能为空',
            trigger: 'blur'
          }],
          productCode: [{
            required: true,
            message: '型号不能为空',
            trigger: 'blur'
          }],
          outNum: [{
            required: true,
            message: '出库数量不能为空',
            trigger: 'blur'
          }]
        },
        typeOptions: [
          {
            value: '0',
            label: '个人'
          },
          {
            value: '1',
            label: '校区'
          }
        ],
        dataList: [],
        dataListTreeProps: {
          label: 'category',
          children: 'children'
        }
      }
    },
    mounted () {
      this.getShopInfo()
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/business/ckout/info/${this.dataForm.productCode}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.dataForm.productCode = data.ckOut.productCode
              }
            })
          }
        })
      },
      changeType () {
        if (this.dataForm.ckOutType === '0') {
          this.shopShow = false
        } else {
          this.shopShow = true
        }
      },
      // 查询一级分类
      getFatherCategory () {
        this.$http({
          url: this.$http.adornUrl('/business/ckcategory/list'),
          method: 'get',
          params: this.$http.adornParams({
          })
        }).then(({
          data
        }) => {
          this.dataList = treeDataTranslate(data, 'id', 'pid')
        })
      },
      // 按分类查询产品
      getProduct (categoryId) {
        let cid = 0
        if (categoryId !== 0) {
          cid = categoryId
        } else {
          cid = ''
        }
        this.$http({
          url: this.$http.adornUrl('/business/ckproduct/listBy'),
          method: 'get',
          params: this.$http.adornParams({
            'categoryId': cid
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.dataForm.product = data.productList
          }
        })
      },
      // 获取机构下所有店铺信息
      getShopInfo () {
        this.$http({
          url: this.$http.adornUrl('/business/student/getShopInfo'),
          mothod: 'get',
          params: {}
        }).then(({data}) => {
          this.shopids = data.list
        })
      },
      // 查询产品
      getProductInfo () {
        this.$http({
          url: this.$http.adornUrl(`/business/ckproduct/info/${this.dataForm.productCode}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.dataForm.leftNum = data.ckProduct.num
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        if (this.dataForm.outNum <= 0) {
          this.$message.error('数量不能为0或负')
          this.dataForm.outNum = 0
          return false
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/business/ckout/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'productCode': this.dataForm.productCode,
                'outNum': this.dataForm.outNum,
                'userId': this.dataForm.userId,
                'mobile': this.dataForm.mobile,
                'address': this.dataForm.address,
                'remark': this.dataForm.remark,
                'creator': this.dataForm.creator,
                'createTime': this.dataForm.createTime,
                'updator': this.dataForm.updator,
                'updateTime': this.dataForm.updateTime,
                'shopId': this.dataForm.shopId,
                'ckOutType': this.dataForm.ckOutType,
                'studentName': this.dataForm.studentName
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 菜单树选中
      dataListTreeCurrentChangeHandle (data, node) {
        this.dataForm.parentId = data.id
        this.dataForm.parentName = data.category
        this.pClose()
        this.getProduct(data.id)
      },
      pClose () {
        this.$refs[`dataListPopover`].doClose()
      }
    }
  }
</script>
